<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-03 00:33:05
 * @LastEditTime: 2022-08-25 21:33:51
 * @LastEditors: CHINAKAIYUAN
 * @Description: 
 */

namespace App\Models;

use App\Repositories\FinanceAcceptancePayDetailsRepository;
use App\Repositories\FinanceVoucherRepository;
use App\Traits\CompanyTrait;
use App\Traits\VoucherTrait;

class FinanceAcceptancePay extends BaseModel
    {
    use CompanyTrait;
    use VoucherTrait;
    public $timestamps = true;
    public $table = "sys_finance_pay_acceptance";
    protected $guarded = [];
    // 
    public function status()
        {
        return $this->belongsTo(Dic::class, "status_id", "key")->where(function ($q)
            {
            $q->where("code", 'status_with_finance');
            });
        }
    public function handlebilltrade()
        {
        return $this->belongsTo(CompanyBilltrade::class);
        }
    public function details()
        {
        return $this->hasMany(FinanceAcceptancePayDetails::class, "main_id");
        }

    public function create_charge($data, $subject, $company)
        {
        $change['code']          = $data['code'];
        $change['billdate']      = $data['billdate'];
        $change['department_id'] = $data['department_id'];
        $change['creator_id']    = $data['creator_id'];
        $change['company']       = $company;
        $change['summary']       = $data['summary'];
        $change['account_id']    = 1121;
        $change['tax']           = 1;
        $change['famount']       = $change['amount'] = $change['net_famount'] = $change['discount_amount'] = 0;
        $change['status']        = 1;
        $change['net_amount']    = $data['amount'];
        $change['subject_id']    = $subject;
        $change['subject']       = M("basedata_subject_model")->gfv($subject, 'name');
        $change['remark']        = "[" . M("trade_model")->gfv($data['trade_id'], 'sname') . "]" . $data['summary'];
        $change['be_create']     = $data['id'];
        $change['created_model'] = "finance_pay_acceptance_details_model";
        FinanceCharge::create($change);
        }

    /**
     * 过账
     *
     * @param  int|string $gdata
     * @return boolean
     */
    public function finance($orders = null)
        {

        $gdata = $orders ?? $this;
        if ($gdata->status_id == 1)
            return false;
        if ($gdata->status_id != 0) {
            fail("单据非审核状态！，无法财审！");
            }

        $gdata->details->map(function ($v) use ($gdata)
            {
            $buf                 = $v->toArray();
            $rec_rec             = $v->acceptance_rec;
            $rec_rec->leftamount -= $v->saleamount;
            if ($rec_rec->leftamount < 0) {
                fail("承兑金额不足！");
                }
            $rec_rec->save();

            $buf['trade_id']             = $rec_rec->handletrade_id;
            $buf['financedepartment_id'] = $gdata['department_id'];
            if (is_numeric(value: $gdata['supplier_id']) && $gdata['supplier_id'] > 0)
                $buf['company_id'] = $gdata['supplier_id'];
            else
                $buf['company_id'] = $gdata->customer_id;
            $summary = '应付承兑 :' . $rec_rec->code;
            // if (!in_array($gdata['subject_id'], [2202, 220202, 220201]))
            //     $this->create_charge($gdata, $gdata['subject_id'], $gdata->customer->name);
            $details               = [];
            $buf['invoice_amount'] = 0;
            // 借：应付/费用 
            $details[] = FinanceVoucherRepository::mergeVoucher($gdata['subject_id'], $summary, $v->saleamount, 0, $buf, 0, 1);
            //贷 应收票据 
            $details[] = FinanceVoucherRepository::mergeVoucher(1121, $summary, 0, $v->saleamount, $buf, 0, 1);

            $voucher = FinanceVoucherRepository::CreateVoucher($gdata->billdate, $rec_rec->handletrade_id, $details, $v, 0);
            FinanceVoucherRepository::auditVoucher($voucher);
            return $buf;
            });

        auditSave($gdata);
        return $gdata;
        }


    public function nofinance($orders = null)
        {
        $v = $orders ?? $this;
        auditSave($v, false);
        $v->details->filter(function ($vv)
            {
            if ($vv->voucher) {
                if ($vv->voucher->status_id == 1) {
                    return FinanceVoucherRepository::auditVoucher($vv->voucher, false);
                    }
                FinanceVoucherRepository::RemoveVoucher($vv->voucher);

                $rec_rec             = $vv->acceptance_rec;
                $rec_rec->leftamount += $vv->saleamount;
                $rec_rec->save();

                }
            });
        }
    }
